using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using SqEngine.Audio;
using sqengine.Engine.Common;
using SqEngine;


namespace sqengine.Components
{
    public class ChatComponent : Microsoft.Xna.Framework.DrawableGameComponent
    {
        private const int _chat_df_cursor_time = 500;
        private const string _chat_df_cursor_char = "_";
        private const string _chat_df_prefix = "> ";

        private const int _chatbar_w = 500;
        private const int _chatbar_h = 20;



        private AdvancedContent _adcontent;
        private SpriteBatch _spritebatch;
        private string _playername;
        private string _chatfont;
        private SpriteFont _chat_fnt;
        private Game _game;
        private bool _enabled = false;
        private bool _prev_enabled = false;
        private string _chat_text = "";
        private string _chat_cursor = _chat_df_cursor_char;
        private double _chat_cursor_time = _chat_df_cursor_time;
        private Texture2D _blank;
        private KeysManager _keyman;
        

        private KeyboardState prevKey;
        private KeyboardState currKey;


        int bbWidth, bbHeight;

        public ChatComponent(Game game, AdvancedContent adcontent, string playername, string chatfont, KeysManager keyman)
            : base(game)
        {
            _adcontent = adcontent;
            _playername = playername;
            _chatfont = chatfont;
            _keyman = keyman;
            _game = game;
        }

        public void Playername(string player)
        {
            _playername = player;
        }

        private void GraphicsDevice_DeviceReset(object sender, EventArgs e)
        {
            bbWidth = GraphicsDevice.PresentationParameters.BackBufferWidth;
            bbHeight = GraphicsDevice.PresentationParameters.BackBufferHeight;
        }

        public bool Active()
        {
            return _enabled;

        }
        public override void Initialize()
        {
            base.Initialize();
        }
        public void Start()
        {
            _enabled = true;
        }

        public void Stop()
        {
            _enabled = false;

        }
        protected override void LoadContent()
        {
            this._game.GraphicsDevice.DeviceReset += new EventHandler(GraphicsDevice_DeviceReset);
            _chat_fnt = _adcontent.LoadSpriteFont(_chatfont);
            _blank = _adcontent.LoadTexture2D("Textures/UI/blank");

            bbWidth = GraphicsDevice.PresentationParameters.BackBufferWidth;
            bbHeight = GraphicsDevice.PresentationParameters.BackBufferHeight;

            base.LoadContent();
        }

        public override void Update(GameTime gameTime)
        {
            if (_enabled)
            {
                string letter = "";

                prevKey = currKey;

                currKey = Keyboard.GetState();
                KeyboardState _keyboard_state = Keyboard.GetState();



                _chat_cursor_time -= gameTime.ElapsedGameTime.TotalMilliseconds;

                if (_chat_cursor_time <= 0)
                {
                    if (_chat_cursor == "")
                        _chat_cursor = _chat_df_cursor_char;
                    else
                        _chat_cursor = "";

                    _chat_cursor_time = _chat_df_cursor_time;

                }



                _chat_text += AddPressedKey();


                if (currKey.IsKeyDown(Keys.Space) && prevKey.IsKeyUp(Keys.Space) && _chat_text != "" && _chat_text[_chat_text.Length - 1].ToString() != " ")
                    _chat_text += " ";


                if (currKey.IsKeyDown(Keys.Back) && prevKey.IsKeyUp(Keys.Back) && _chat_text != "")
                {
                    _chat_text = _chat_text.Remove(_chat_text.Length - 1, 1);

                }

                if (currKey.IsKeyDown(Keys.Enter) && prevKey.IsKeyUp(Keys.Enter) && _chat_text != "")
                {
                    SendMessage(_chat_text);
                    _chat_text = "";
                }
            }
            base.Update(gameTime);
        }


        public void ChatEnable(bool state)
        {
            if (state)
            {
                _prev_enabled = _enabled;
                _enabled = !_enabled;
            }

        }

        public void SendMessage(string message)
        {
            ((sqengine)_game).ChatSendMessage(_playername, message);

        }

        public override void Draw(GameTime gameTime)
        {
            if (_spritebatch == null)
                _spritebatch = new SpriteBatch(_game.GraphicsDevice);

            if (_enabled)
            {
                _spritebatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.SaveState);

                //Draw Chat bar
                _spritebatch.Draw(_blank, new Rectangle(10, bbHeight - 60, _chatbar_w, _chatbar_h), Color.White);
                _spritebatch.Draw(_blank, new Rectangle(11, bbHeight - 59, _chatbar_w - 2, _chatbar_h - 2), Color.Black);

                _spritebatch.DrawString(_chat_fnt, _playername + _chat_df_prefix + _chat_text + _chat_cursor, new Vector2(13, bbHeight - 57), Color.White);

                _spritebatch.End();

                ((sqengine)_game).RestoreRenderState();

            };



            base.Draw(gameTime);
        }

        public string AddPressedKey()
        {


            string letter = "";

            for (int i = 0; i < _keyman._keys.Length; i++)
            {
                if (currKey.IsKeyDown(_keyman._keys[i]) && prevKey.IsKeyUp(_keyman._keys[i]))
                {

                    switch (_keyman._keys[i])
                    {
                        case (Keys.D0):
                            letter = "=";
                            break;
                        case (Keys.D1):
                            letter = "!";
                            break;

                        case (Keys.D2):
                            letter = "\"";
                            break;

                        case (Keys.D3):
                            letter = "^";
                            break;

                        case (Keys.D4):
                            letter = "$";
                            break;
                        case (Keys.D5):
                            letter = "%";
                            break;

                        case (Keys.D6):
                            letter = "&";
                            break;

                        case (Keys.D7):
                            letter = "/";
                            break;

                        case (Keys.D8):
                            letter = "(";
                            break;

                        case (Keys.D9):
                            letter = ")";
                            break;

                        case (Keys.OemQuestion):
                            letter = "?";
                            break;

                        case (Keys.OemMinus):
                            letter = "_";
                            break;

                        case (Keys.OemPipe):
                            letter = "\\";
                            break;
                        case (Keys.OemPeriod):
                            letter = ":";
                            break;

                        default:
                            letter = _keyman._keys[i].ToString();
                            break;


                    }

                    if (currKey.IsKeyUp(Keys.LeftShift) && currKey.IsKeyUp(Keys.RightShift))
                    {
                        if (letter == "!") { letter = "1"; }
                        else if (letter == "\"") { letter = "2"; }
                        else if (letter == "^") { letter = "3"; }
                        else if (letter == "$") { letter = "4"; }
                        else if (letter == "%") { letter = "5"; }
                        else if (letter == "&") { letter = "6"; }
                        else if (letter == "/") { letter = "7"; }
                        else if (letter == "(") { letter = "8"; }
                        else if (letter == ")") { letter = "9"; }
                        else if (letter == "=") { letter = "0"; }
                        else if (letter == ":") { letter = "."; }
                        else if (letter == "_") { letter = "-"; }
                        else { letter = letter.ToLower(); }
                    }


                    return letter;

                }
            }

            return "";

        }
    }
}